//
//  registryEditController.m
//  SoundPill
//
//  Created by 宋鹏鹏 on 15/5/5.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "registryEditController.h"
#import "AppDelegate.h"
#import "imageVPickController.h"
//上传
#import "QiniuSDK.h"
#import "AFNetworking.h"
#import "JSONKit.h"

#import "UIViewExt.h"
#import "AddTagViewController.h"
#import "registLoginView.h"
#import "registSexView.h"
#import "JCAlertView.h"
#import "LCActionSheet.h"
@interface registryEditController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UIAlertViewDelegate,UITextFieldDelegate>
{
    
    UIButton *_lastSelect;
    UIPickerView *locatiaonView;
    //pickView data
    NSArray *pickViewData;
    UIView *view1;
    UIView *view2;
    NSString *_provincesString;
    NSString *_cityString;
    
    //////用户头像路径
    NSString *headImageFilePath;
    NSString *nameFilePath;
    NSString *userSex;
    NSString *locationFilePath;
    
    /*上传*/
    NSString *token;
    
    //
    UIButton *cancelBtn;
    UIButton *sureBtn;
    //
    UIButton *sexCancelBtn;
    UIButton *sexSureBtn;
    
    //
    UIView *grayBackGround;
    //
    UIPickerView *sexPickView;
    NSArray *sexData;
    
    UILabel *headlabel;
    //头像
    UIImageView *headImage;
    //昵称
    registLoginView *_name;
    //个人介绍
    registLoginView *_introduce;
    //性别
    registSexView *_sex;
    //所在地
    registSexView *_location;
    
    //
    UIButton *completeItem;
    //
    BOOL isHeadImageNil;
    BOOL isNameNil;
    BOOL isSexNil;
    BOOL isLocationNil;
    
    NSString *initSex;
    NSString *initLocation;
    UILabel *avatarAlertLabel;
    JCAlertView *_alert;
}
@end

@implementation registryEditController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0) {
        
        self.edgesForExtendedLayout=UIRectEdgeNone;
        
    }
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor],NSForegroundColorAttributeName,nil]];
   //
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 添加右边完成按钮
    completeItem = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    [completeItem setImage:[UIImage imageNamed:@"done"] forState:UIControlStateNormal];
    [completeItem addTarget:self action:@selector(completeClick) forControlEvents:UIControlEventTouchUpInside];
    // 添加rightItem
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:completeItem];
    self.navigationItem.rightBarButtonItem=rightItem;
    
    //清除本地头像
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *headImageFile = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    [fileManager removeItemAtPath:headImageFile error:nil];

    
    sexData = [[NSArray alloc] initWithObjects:@"男",@"女",@"外星人",nil];
    self.title=@"设置个人信息";
    
    //self.view.backgroundColor = [UIColor whiteColor];
    
    //头像
    headImage = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.width *0.35, 20, self.view.width *0.3, self.view.width *0.3)];
    headImage.center = CGPointMake(self.view.width / 2, 20 + headImage.frame.size.height / 2);
    headImage.image=[UIImage imageNamed:@"regist_addHead"];
    isHeadImageNil = YES;
    headImage.layer.cornerRadius = headImage.frame.size.height/2.0;
    headImage.layer.masksToBounds = YES;
    
    headImage.layer.borderWidth = 0;
    headImage.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(registerHeadClick)];
    [headImage addGestureRecognizer:tapGestureRecognizer];
    
    [self.view addSubview:headImage];
    
    //昵称
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, headImage.bottom + 27 , 40, 30)];
    nameLabel.text = @"昵称";
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:nameLabel];
    //昵称输入框
    _name = [[registLoginView alloc] initWithFrame:CGRectMake(nameLabel.right+10, nameLabel.top, self.view.width - 40 - nameLabel.width - 10, 30) image:[UIImage imageNamed:@"nil"] placeHold:@"请输入昵称"];
    _name.layer.borderColor = [[UIColor blackColor]CGColor];
    _name.layer.borderWidth = 2;
    _name.field.delegate = self;
    _name.field.enablesReturnKeyAutomatically = YES;
    [self.view addSubview:_name];
    //个人介绍
//    UILabel *introduceLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.width *0.15, nameLabel.bottom + 10, 60, 30)];
//    introduceLabel.text = @"签名";
//    introduceLabel.textColor = [UIColor lightGrayColor];
//    introduceLabel.textAlignment = NSTextAlignmentCenter;
//    introduceLabel.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:introduceLabel];
//    //个人介绍输入框
//    _introduce = [[registLoginView alloc] initWithFrame:CGRectMake( introduceLabel.right+5, introduceLabel.top, self.view.width*0.5, 30) image:[UIImage imageNamed:@"nil"] placeHold:@"请输入签名"];
//    _introduce.layer.borderColor = [[UIColor blackColor]CGColor];
//    _introduce.layer.borderWidth = 2;
//    _introduce.field.delegate = self;
//    _introduce.field.enablesReturnKeyAutomatically = YES;
//    [self.view addSubview:_introduce];
    //性别
    UILabel *sexLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 ,_name.bottom + 10 , 40, 30)];
    sexLabel.text = @"性别";
    sexLabel.textColor = [UIColor blackColor];
    sexLabel.textAlignment = NSTextAlignmentCenter;
    sexLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:sexLabel];
    //性别输入框
    initSex = @"外星人";
    _sex = [[registSexView alloc] initWithFrame:CGRectMake(nameLabel.right+10, sexLabel.top, _name.width, 30) image:[UIImage imageNamed:@"aliens_btn"] placeHold:@"未设置"];
    _sex.field.text = initSex;
    [[NSUserDefaults standardUserDefaults] setValue:@"外星人" forKey:@"sex"];
    _sex.userInteractionEnabled = YES;
    _sex.layer.borderColor = [[UIColor blackColor]CGColor];
    _sex.layer.borderWidth = 2;
    UITapGestureRecognizer *sexTapGestureRecognizer = [[UITapGestureRecognizer alloc]
                                                    initWithTarget:self
                                                    action:@selector(userSexClick)];
    [_sex addGestureRecognizer:sexTapGestureRecognizer];
    [self.view addSubview:_sex];
    
    //地区
    UILabel *locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, sexLabel.bottom + 10 , 40, 30)];
    locationLabel.text = @"地区";
    locationLabel.textColor = [UIColor blackColor];
    locationLabel.textAlignment = NSTextAlignmentCenter;
    locationLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:locationLabel];
    //地区输入框
    initLocation = self.locationStr;
    _location = [[registSexView alloc] initWithFrame:CGRectMake(nameLabel.right+10, locationLabel.top, _name.width, 30) image:[UIImage imageNamed:@"location_btn"] placeHold:@"未设置"];
    _location.field.text = initLocation;
    [[NSUserDefaults standardUserDefaults] setValue:initLocation forKey:@"location"];
    _location.layer.borderColor = [[UIColor blackColor]CGColor];
    _location.layer.borderWidth = 2;
    _location.userInteractionEnabled = YES;
    UITapGestureRecognizer *locatinTapGestureRecognizer = [[UITapGestureRecognizer alloc]
                                                       initWithTarget:self
                                                       action:@selector(userLocationClick)];
    [_location addGestureRecognizer:locatinTapGestureRecognizer];
    [self.view addSubview:_location];


    
    grayBackGround = [[UIView alloc]initWithFrame:CGRectMake(0, _location.frame.origin.y + _location.frame.size.height + 5, self.view.width, self.view.height*0.5)];
    grayBackGround.backgroundColor =[UIColor whiteColor];
    [self.view addSubview:grayBackGround];
    grayBackGround.alpha = 0;
    
    //
    isHeadImageNil = YES;
    isSexNil  = YES;
    isNameNil = YES;
    isLocationNil = YES;
    
    completeItem.hidden = YES;
    
}
- (void)completeClick
{
    [self postUserSex:_sex.field.text];
    [self postUserLocation:_location.field.text];
    
    if (isHeadImageNil == NO && isNameNil == NO) {
        
        //设置标签
        AddTagViewController *addTag = [[AddTagViewController alloc] initWithTitle:@"关注标签"];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:addTag];
        [self presentViewController:nav animated:YES completion:nil];
        //进入首页
        //跳到广场
    }else{
        if (isHeadImageNil == YES) {
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"请设置你的头像" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
            
        }else{
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"请完善个人信息" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        }
    
    }
    

}
//
- (void)registerHeadClick
{
    [self sexCancelClick];
    [self cancelClick];
    
    if (locatiaonView!=nil) {
        [self cancelClick];
    }
    
    _lastSelect.selected = NO;
    //
    [self takePictureClick];
    
}
//
- (void)userNameClick
{
    [self sexCancelClick];
    [self cancelClick];
    if (locatiaonView!=nil) {
        [self cancelClick];
    }
    _lastSelect.selected = NO;
    
}

#pragma mark - 设置性别
- (void)userSexClick
{
    grayBackGround.frame = CGRectMake(0, self.view.height - self.view.height * 0.4, self.view.width, self.view.height*0.4);
    if (locatiaonView!=nil) {
        [self cancelClick];
    }
    _lastSelect.selected = NO;
    grayBackGround.alpha =1;
    
    //    editSexController *sexVC = [[editSexController alloc]init];
    //    [self.navigationController pushViewController:sexVC animated:YES];
    
    if (sexPickView==nil) {
        //显示选择性别的滚动轴
        //
        sexPickView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 40, self.view.width,self.view.height*0.25)];
        sexPickView.backgroundColor = [UIColor clearColor];
        
        sexPickView.tag = 100001;
        sexPickView.delegate = self;
        sexPickView.dataSource = self;
        
        //第二种
        // NSString *path = [[NSBundle mainBundle]pathForResource:@"city" ofType:@"plist"];
        //pickViewData = [[NSArray alloc] initWithContentsOfFile:path];
        
        [grayBackGround addSubview:sexPickView];
        
        sexCancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.03, 10, self.view.width*0.25, 30)];
        sexCancelBtn.backgroundColor = [UIColor clearColor];
        [sexCancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [sexCancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [sexCancelBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [sexCancelBtn addTarget:self action:@selector(sexCancelClick) forControlEvents:UIControlEventTouchUpInside];
        
        [grayBackGround addSubview:sexCancelBtn];
        
        
        sexSureBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.72, 10, self.view.width*0.25, 30)];
        sexSureBtn.backgroundColor = [UIColor clearColor];
        [sexSureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [sexSureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [sexSureBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [sexSureBtn addTarget:self action:@selector(sexSureClick) forControlEvents:UIControlEventTouchUpInside];
        [grayBackGround addSubview:sexSureBtn];
        
    }
    
    //
    //_userSex.textLabel.text = @"男";
    _sex.field.text = @"男";
    if([_sex.field.text isEqualToString:@"男"]){
        _sex.image.image = [UIImage imageNamed:@"man_btn"];
    }else if ([_sex.field.text isEqualToString:@"女"]){
        _sex.image.image = [UIImage imageNamed:@"girl_btn"];
    }else{
        _sex.image.image = [UIImage imageNamed:@"aliens_btn"];
    }

    
    
}
- (void)sexCancelClick
{
    _sex.field.text = initSex;
    if([_sex.field.text isEqualToString:@"男"]){
        _sex.image.image = [UIImage imageNamed:@"man_btn"];
    }else if ([_sex.field.text isEqualToString:@"女"]){
        _sex.image.image = [UIImage imageNamed:@"girl_btn"];
    }else{
        _sex.image.image = [UIImage imageNamed:@"aliens_btn"];
    }
    sexPickView.alpha = 0;
    sexPickView = nil;
    [sexPickView removeFromSuperview];
    [sexCancelBtn removeFromSuperview];
    [sexSureBtn removeFromSuperview];
    grayBackGround.alpha = 0;
    
}
- (void)sexSureClick
{
    if (_sex.field.text!=nil) {
        [sexPickView removeFromSuperview];
        sexPickView =nil;
        [sexCancelBtn removeFromSuperview];
        [sexSureBtn removeFromSuperview];
        grayBackGround.alpha = 0;
        isSexNil = NO;
        initSex = _sex.field.text;
    }
}
#pragma mark------传Sex
- (void)postUserSex:(NSString *)sex
{
//    NSLog(@"Sex 是%@",sex);
    NSString *sexvn = sex;
    
    if ([sexvn isEqualToString:@"男"]) {
        sexvn = @"1";
    }else if ([sex isEqualToString:@"女"]) {
        sexvn = @"2";
    }else if ([sex isEqualToString:@"外星人"]) {
        sexvn = @"0";
    }
    
    //发请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid =[userDefaultes objectForKey:@"uid"];
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic setObject:sexvn forKey:@"sex"];
    if (uid!=nil) {
        [dataDic setObject:uid forKey:@"user"];
    }else{
    
    }
      NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",uid];
      NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
//    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"token"]);
//    NSLog(@"%@",header);
    
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:str parameters:dataDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
        //读取字典类型NSDictionary类型的数据
        NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:myDictionary];
        [dic setValue:sex forKey:@"sex"];
        myDictionary = dic;
        [userDefaultes setObject:myDictionary forKey:@"myDictionary"];
        //        NSLog(@"%@",myDictionary);
        //保存location（注册成功后）
        [userDefaultes setObject:sex forKey:@"sex"];
        [userDefaultes synchronize];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [JCAlertView showOneButtonWithTitle:@"网络异常" Message:@"确保在有Wifi或信号良好的地方重试" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
            
        }];
    }];
}

//
- (void)userLocationClick
{
    
    //取消性别设置
    [self sexCancelClick];
    
    _lastSelect.selected = NO;
    grayBackGround.alpha = 1;
    
    if (locatiaonView ==nil) {
        
        locatiaonView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 30, self.view.width,self.view.height*0.45)];
        locatiaonView.backgroundColor = [UIColor clearColor];
        locatiaonView.tag =100000;
        
        locatiaonView.delegate = self;
        locatiaonView.dataSource = self;
        
        //第二种
        NSString *path = [[NSBundle mainBundle]pathForResource:@"city" ofType:@"plist"];
        pickViewData = [[NSArray alloc] initWithContentsOfFile:path];
        
        
        //
        [grayBackGround addSubview:locatiaonView];
        
        cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.03, 10, self.view.width*0.25, 30)];
        cancelBtn.backgroundColor = [UIColor clearColor];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [cancelBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [cancelBtn addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
        
        [grayBackGround addSubview:cancelBtn];
        
        
        sureBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.72, 10, self.view.width*0.25, 30)];
        sureBtn.backgroundColor = [UIColor clearColor];
        [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [sureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [sureBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [sureBtn addTarget:self action:@selector(locationSureClick) forControlEvents:UIControlEventTouchUpInside];
        [grayBackGround addSubview:sureBtn];
        
    }
    _location.field.text = initLocation;
    if (![initLocation isEqualToString:@"火星"]) {
        NSArray *IL = [initLocation componentsSeparatedByString:@" "];
        for (int i = 0; i < pickViewData.count; i++ ) {
            NSDictionary *dict = pickViewData[i];
            if ([[dict valueForKey:@"state"] isEqualToString:IL[0]]) {
                [locatiaonView selectRow:i inComponent:0 animated:NO];
                [locatiaonView reloadComponent:1];
            }
        }
    } else {
        _location.field.text = @"北京 东城区";
        [locatiaonView selectRow:0 inComponent:0 animated:NO];
        [locatiaonView reloadComponent:1];
    }
}
#pragma mark - 按钮事件
- (void)cancelClick
{
    locatiaonView.alpha = 0;
    locatiaonView = nil;
    [locatiaonView removeFromSuperview];
    [cancelBtn removeFromSuperview];
    [sureBtn removeFromSuperview];
    grayBackGround.alpha = 0;
    _location.field.text = initLocation;
}
- (void)locationSureClick
{
    if (_location.field.text!=nil) {
        [locatiaonView removeFromSuperview];
        locatiaonView = nil;
        [cancelBtn removeFromSuperview];
        [sureBtn removeFromSuperview];
        grayBackGround.alpha = 0;
        initLocation = _location.field.text;
    }
    
}

#pragma mark - UIPickerView delegate
//返回有列数 Component列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    if (pickerView == sexPickView ) {
        return 1;
    }else
        return 2;
    
}

//返回每一列中的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    if (pickerView == sexPickView) {
        return sexData.count;
    }else{
        
        //return 10;
        
        if (component == 0) {//第一列
            return pickViewData.count;
        }
        
        //返回第一列选择的行的索引
        NSInteger selectedRow = [pickerView selectedRowInComponent:0];
        //取得省级字典
        NSDictionary *items = [pickViewData objectAtIndex:selectedRow];
        //取得该省下所有的市
        NSArray *cities = [items objectForKey:@"cities"];
        
        return cities.count;
    }
    
}

//返回每个item中的title  实际上返回的就是一个label
- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component {
    if (pickerView == sexPickView){
        
        NSString *state = sexData[row];

        return state;
    }else{
        
        if (component == 0) {//第一列
            NSDictionary *dic = [pickViewData objectAtIndex:row];
            NSString *state = [dic objectForKey:@"state"];
            return state;
        }
        
        //返回第一列选择的行的索引
        NSInteger selectedRow = [pickerView selectedRowInComponent:0];
        //取得省级字典
        NSDictionary *items = [pickViewData objectAtIndex:selectedRow];
        //取得该省下所有的市
        NSArray *cities = [items objectForKey:@"cities"];
        NSString *cityName = [cities objectAtIndex:row];
                return cityName;
    }
    return nil;
}

//选择行的事件
- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component {
    
    if (pickerView == sexPickView) {
        NSString *cityName1 = sexData[row];
        if (cityName1!=nil) {
            _sex.field.text = cityName1;
            if([_sex.field.text isEqualToString:@"男"]){
                _sex.image.image = [UIImage imageNamed:@"man_btn"];
            }else if ([_sex.field.text isEqualToString:@"女"]){
                _sex.image.image = [UIImage imageNamed:@"girl_btn"];
            }else{
                _sex.image.image = [UIImage imageNamed:@"aliens_btn"];
            }
        }
        
    }else{
        if (component == 0) {
            //刷新指定列中的行
            [pickerView reloadComponent:1];
            //选择指定的item
            [pickerView selectRow:0 inComponent:1 animated:NO];
            //
            NSDictionary *dic = [pickViewData objectAtIndex:row];
            NSString *state = [dic objectForKey:@"state"];
            _provincesString = state;
            
            //返回第一列选择的行的索引
            NSInteger selectedRow = [pickerView selectedRowInComponent:0];
            //取得省级字典
            NSDictionary *items = [pickViewData objectAtIndex:selectedRow];
            //取得该省下所有的市
            NSArray *cities = [items objectForKey:@"cities"];
            
            NSString *cityName1 = [cities objectAtIndex:0];
            _cityString = cityName1;
            
        } else if (component == 1) {
            
            if (_provincesString==nil) {
                NSDictionary *dic = [pickViewData objectAtIndex:0];
                NSString *state = [dic objectForKey:@"state"];
                _provincesString = state;
            } else {
                
            }
            
            //
            //返回第一列选择的行的索引
            NSInteger selectedRow = [pickerView selectedRowInComponent:0];
            //取得省级字典
            NSDictionary *items = [pickViewData objectAtIndex:selectedRow];
            //取得该省下所有的市
            NSArray *cities = [items objectForKey:@"cities"];
            
            NSString *cityName1 = [cities objectAtIndex:row];
            _cityString = cityName1;
            
        }
        _location.field.text = [NSString stringWithFormat:@"%@ %@",_provincesString,_cityString];
    }
}
//选中第一行


////设置列的宽度
//- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
//    if (component == 0) {
//        return 200;
//    }
//    return 100;
//}

//自定义行中显示的view
- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)view {
    
    if (pickerView == sexPickView) {
        view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
        
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
        
        NSString *state = sexData[row];
        label.text=state;
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment=NSTextAlignmentCenter;
        [view addSubview:label];
        
        view.backgroundColor = [UIColor clearColor];
        return view;
        
    }else{
        
        if (component == 0) {
            view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
            
            UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
            NSDictionary *dic = [pickViewData objectAtIndex:row];
            NSString *state = [dic objectForKey:@"state"];
            label.text=state;
            label.backgroundColor = [UIColor clearColor];
            label.textAlignment=NSTextAlignmentCenter;
            [view1 addSubview:label];
            
            view1.backgroundColor = [UIColor clearColor];
            return view1;
        }else if(component == 1){
            
            view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
            UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
            //返回第一列选择的行的索引
            NSInteger selectedRow = [pickerView selectedRowInComponent:0];
            //取得省级字典
            NSDictionary *items = [pickViewData objectAtIndex:selectedRow];
            //取得该省下所有的市
            NSArray *cities = [items objectForKey:@"cities"];
            if (row<cities.count) {
                NSString *cityName1 = [cities objectAtIndex:row];
                
                label.text=cityName1;
            }
            
            label.textColor = [UIColor blackColor];
            label.backgroundColor = [UIColor clearColor];
            label.textAlignment=NSTextAlignmentCenter;
            [view2 addSubview:label];
            
            view2.backgroundColor = [UIColor clearColor];
            
            return view2;
        }
    }
    return nil;
}



//弹出actionsheet。选择获取头像的方式
//从相册获取图片
-(void)takePictureClick
{
    avatarAlertLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
    avatarAlertLabel.backgroundColor = [UIColor whiteColor];
    avatarAlertLabel.text = @"正在上传头像...";
    avatarAlertLabel.textAlignment = NSTextAlignmentCenter;
    avatarAlertLabel.layer.borderColor = [[UIColor blackColor] CGColor];
    avatarAlertLabel.layer.borderWidth = 2;
    
    LCActionSheet *actionSheet = [LCActionSheet sheetWithTitle:@"请选择图片来源" buttonTitles:@[@"拍照",@"相册"] redButtonIndex:-1 clicked:^(NSInteger buttonIndex) {
        switch (buttonIndex) {
            case 0://照相机
            {
                imageVPickController *imagePicker = [[imageVPickController alloc] init];
                imagePicker.delegate = self;
                imagePicker.allowsEditing = YES;
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imagePicker animated:YES completion:nil];
            }
                break;
            case 1://本地相簿
            {
                imageVPickController *imagePicker = [[imageVPickController alloc] init];
                imagePicker.delegate = self;
                imagePicker.allowsEditing = YES;
                imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                // [self presentModalViewController:imagePicker animated:YES];
                [self presentViewController:imagePicker animated:YES completion:nil];
            }
                break;
        }
    }];
    [actionSheet show];
}
#pragma mark -
#pragma UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    [self registSaveImage:img];
    [self performSelector:@selector(getToken) withObject:nil afterDelay:0.2];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //设置导航栏样式
    //[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    //    [picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)registSaveImage:(UIImage *)image {
//        NSLog(@"保存头像！");
    //    [userPhotoButton setImage:image forState:UIControlStateNormal];
    
    //显示loading
    [self loadingAnimation:image];
    
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    headImageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
//    NSLog(@"imageFile->>%@",headImageFilePath);
    success = [fileManager fileExistsAtPath:headImageFilePath];
    if(success) {
        success = [fileManager removeItemAtPath:headImageFilePath error:&error];
    }
    //    UIImage *smallImage=[self scaleFromImage:image toSize:CGSizeMake(80.0f, 80.0f)];//将图片尺寸改为80*80
//    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(170, 170)];
    [UIImageJPEGRepresentation(image, 1.0f) writeToFile:headImageFilePath atomically:YES];//写入文件
    //UIImage *selfPhoto = [UIImage imageWithContentsOfFile:headImageFilePath];//读取图片文件
    //    [userPhotoButton setImage:selfPhoto forState:UIControlStateNormal];
    //self.img.image = selfPhoto;
    //_editHead.headImage.image = selfPhoto;
}

// 改变图像的尺寸，方便上传服务器
- (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
//2.保持原来的长宽比，生成一个缩略图
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}

#pragma mark -
#pragma mark 上传
- (void)getToken{
    _alert = [[JCAlertView alloc] initWithCustomView:avatarAlertLabel dismissWhenTouchedBackground:NO];
    [_alert show];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"1" forKey:@"type"];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
//    NSLog(@"%@",header);
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager GET:@"http://123.57.1.143/api/uptoken?type=3" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        //        NSLog(@"token成功：%@", dic);
        token = [dic objectForKey:@"token"];
        
        [self putHeadFileToQN:headImageFilePath];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        avatarAlertLabel.text = @"上传头像失败";
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:0.7];
        headImage.image=[UIImage imageNamed:@"regist_addHead"];
    }];
}
#pragma mark------传头像
- (void)putHeadFileToQN:(NSString *)headImagePath{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaultes objectForKey:@"uid"];
    
    NSMutableDictionary *optionDic = [NSMutableDictionary dictionary];
    [optionDic setObject:@"3" forKey:@"x:type"];
    [optionDic setObject:uid forKey:@"x:uid"];
//    NSLog(@"===%@",uid);
    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil progressHandler:nil params:optionDic checkCrc:NO cancellationSignal:nil];
    
    QNUploadManager *manager = [[QNUploadManager alloc] init];
//    NSLog(@"-------%@",headImagePath);
    [manager putFile:headImagePath key:nil token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
//        NSLog(@"info:%@", info.error);
//        NSLog(@"resp:%@", resp);
        
        if (resp == nil) {
//            NSLog(@"上传失败");
            avatarAlertLabel.text = @"上传头像失败";
            [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:0.7];
            headImage.image=[UIImage imageNamed:@"regist_addHead"];
        } else {
            [self postHeadImage:[resp objectForKey:@"url"]];
        }
    } option:option];
}

- (void)postHeadImage:(NSString *)uploadId
{
//    NSLog(@"uploedId 是%@",uploadId);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaultes objectForKey:@"uid"];
    
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic setObject:uploadId forKey:@"avatar"];
    [dataDic setObject:uid forKey:@"user"];
    
    
    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",uid];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    
//     NSLog(@"%@",header);
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:str parameters:dataDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        isHeadImageNil = NO;
        avatarAlertLabel.text = @"上传头像成功";
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:0.7];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        avatarAlertLabel.text = @"上传头像失败";
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:0.7];
        headImage.image=[UIImage imageNamed:@"regist_addHead"];
        
    }];
}
#pragma mark------传location
- (void)postUserLocation:(NSString *)location
{
//    NSLog(@"UserLocation 是%@",location);
    //NSString *str2 = [location stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaultes objectForKey:@"uid"];
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic setObject:location forKey:@"location"];
    if (uid!=nil) {
        [dataDic setObject:uid forKey:@"user"];
    }else{
//        NSLog(@"uid 为空？？？");
        
    }
    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",uid];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:str parameters:dataDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
        //读取字典类型NSDictionary类型的数据
        NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:myDictionary];
        [dic setValue:location forKey:@"location"];
        myDictionary = dic;
        [userDefaultes setObject:myDictionary forKey:@"myDictionary"];
        //        NSLog(@"%@",myDictionary);
        //保存location（注册成功后）
        [userDefaultes setObject:location forKey:@"location"];
        [userDefaultes synchronize];
        //
        isLocationNil = NO;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [JCAlertView showOneButtonWithTitle:@"网络异常" Message:@"确保在有Wifi或信号良好的地方重试" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
            
        }];
        
    }];
}

#pragma mark------传UserName
- (void)postUserName:(NSString *)name type:(NSString *)type
{
//    NSLog(@"postUserName 是%@",name);
    //
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaultes objectForKey:@"uid"];
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic setObject:name forKey:type];
    if (uid!=nil) {
        [dataDic setObject:uid forKey:@"user"];
    }else{
//        NSLog(@"uid 为空？？？");
    }
    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",uid];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:str parameters:dataDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
        //读取字典类型NSDictionary类型的数据
        NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:myDictionary];
        [dic setValue:name forKey:type];
        myDictionary = dic;
        [userDefaultes setObject:myDictionary forKey:@"myDictionary"];
        //        NSLog(@"%@",myDictionary);
        //保存名字（注册成功后）
        [userDefaultes setObject:name forKey:type];
        [userDefaultes synchronize];
        //
        isNameNil = NO;
        if ([type isEqualToString:@"username"]) {
            _name.field.text =nil;
            _name.field.text = name;
        } else if ([type isEqualToString:@"introduce"]){
            _introduce.field.text = nil;
            _introduce.field.text = name;
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
        NSInteger statusCode = response.statusCode;
        if (statusCode == 422) {
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"此用户名已被使用" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        } else {
            [JCAlertView showOneButtonWithTitle:@"网络异常" Message:@"确保在有Wifi或信号良好的地方重试" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        }
    }];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (alertView.tag ==100008) {
        if (buttonIndex == 0) {
            
        }else if (buttonIndex == 1){
            
            [self sexSureClick];
        }
    }else if(alertView.tag ==100009)
    {
    
    }else{
        
        if (buttonIndex == 0) {
            
        }else if (buttonIndex == 1){
            
            [self locationSureClick];
            
        }
    }
    
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_name.field resignFirstResponder];
    [_introduce.field resignFirstResponder];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [_name.field resignFirstResponder];
    [_introduce.field resignFirstResponder];
    if (textField == _name.field) {
        [self postUserName:_name.field.text type:@"username"];
    }
//    if (textField == _introduce.field) {
//        [self postUserName:_introduce.field.text type:@"introduce"];
//    }
    return YES;
}

//
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [_name.field addTarget:self action:@selector(textLengthChange:) forControlEvents:UIControlEventEditingChanged];
    [self cancelClick];
    [self sexCancelClick];
    
}
//实现textLengthChange方法
-(void)textLengthChange:(id)sender{
    
    if (_name.field.text.length<=0 ) {
        [sureBtn setEnabled:NO];
        
    }else{
        [sureBtn setEnabled:YES];
        
    }
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == _name.field) {
        if (_name.field.text.length<=0 ) {
            completeItem.hidden =YES;
            
        }else{
            [sureBtn setEnabled:YES];
            completeItem.hidden = NO;
            [self postUserName:_name.field.text type:@"username"];
        }
    }
    if (textField == _introduce.field) {
        if (_introduce.field.text.length<=0 ) {
            completeItem.hidden =YES;
            
        }else{
            [sureBtn setEnabled:YES];
            completeItem.hidden = NO;
            [self postUserName:_name.field.text type:@"introduce"];
        }
    }
    

}
//loading动画
- (void)loadingAnimation:(UIImage *)ima
{
    [UIView animateWithDuration:0.5 animations:^{
        cover = [[UIView alloc]initWithFrame:CGRectMake(self.view.width *0.35, 20, self.view.width *0.3, self.view.width *0.3)];
        cover.backgroundColor = [UIColor whiteColor];
        cover.alpha = 0.5;
        [self.view addSubview:cover];
        _loadingImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.width *0.3, self.view.width *0.3)];
        _loadingImage.backgroundColor = [UIColor clearColor];
        NSArray *animation = [NSArray arrayWithObjects:[UIImage imageNamed:@"loadingAnimationblack1"],[UIImage imageNamed:@"loadingAnimationblack2"], [UIImage imageNamed:@"loadingAnimationblack3"],[UIImage imageNamed:@"loadingAnimationblack4"],[UIImage imageNamed:@"loadingAnimationblack5"],[UIImage imageNamed:@"loadingAnimationblack6"], [UIImage imageNamed:@"loadingAnimationblack7"],[UIImage imageNamed:@"loadingAnimationblack8"],[UIImage imageNamed:@"loadingAnimationblack9"],[UIImage imageNamed:@"loadingAnimationblack10"],[UIImage imageNamed:@"loadingAnimationblack11"],nil];
        _loadingImage.animationImages = animation;
        _loadingImage.animationDuration = 0.5;
        _loadingImage.animationRepeatCount = 4;
        //        _loadingImage.image = [UIImage imageNamed:@"loadingAnimation3"];
        [_loadingImage startAnimating];
        [cover addSubview:_loadingImage];
        
    }completion:^(BOOL finished) {
        
        [_loadingImage removeFromSuperview];
         _loadingImage = nil;
        
        [cover removeFromSuperview];
        cover = nil;
        headImage.image = ima;
        
    }];
    
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
